import { defineStore } from 'pinia'
import { ref, computed, onMounted, getCurrentInstance } from 'vue'
import {
  login,
  register,
  createNotice,
  getReport,
  getUser,
  logout,
  createEvent,
  getEvent
} from '@/request'
import { useRouter } from 'vue-router'
import createDraw from '@/ol-api/createDraw'
import {
  setLineStyle,
  setAreaStyle,
  ToGeoJSON,
  JSONToFeature,
} from '@/ol-api/index'
import { asyncGetDocInfo } from '@/mapgis-api/asyncGetDocInfo'
import Query from '@/mapgis-api/Query'

export const useMapgisStore_hjh = defineStore('mapgis-hjh', () => {
  const router = useRouter() //路由对象
  const type = ref('common') //登录用户的类型
  const username = ref('') //登录用户名
  const password = ref('') //登录密码
  const registerUsername = ref('') //注册的用户名
  const registerPassword = ref('') //注册的密码
  const registerConfirmPassword = ref('') //注册的确认密码
  const createNoticeIsShow = ref(false) //发布公告是否显示
  const noticeIsShow = ref(false) //公告是否显示
  let draw = null //画笔
  const areaList = ref([]) //缓冲区内的小区列表
  let page = ref(1) //发布公告中小区列表的当前页数从1开始
  const all = computed(() => areaList.value.length) // //小区总数
  const search = ref('') //搜索框内容
  const title = ref('') //发布公告的标题
  const textarea = ref('') //发布公告的内容
  const noticeList = ref([]) //公告列表
  //每页显示的小区数据
  const filterTableData = computed(() => {
    let result = areaList.value.slice((page.value - 1) * 5, page.value * 5)
    return result.filter(
      (data) =>
        !search.value ||
        data.name.toLowerCase().includes(search.value.toLowerCase())
    )
  })

  //x轴分页器变化事件
  const handleChange = (val) => {
    page.value = val
  }
  const { proxy } = getCurrentInstance()

  onMounted(async () => {
    const res = await asyncGetDocInfo('guanggu')
  })

  //登录的方法
  const handleLogin = async () => {
    // //发送登录请求
    const res = await login({
      username: username.value,
      password: password.value,
      type: type.value,
    })
    //res.code === 200 登录成功
    if (res.code === 200) {
      localStorage.setItem('username', username.value)
      localStorage.setItem('type', type.value)
      //登录成功后，跳转到对应的页面
      if (type.value === 'common') {
        //本地存储用户信息
        localStorage.setItem('path', 'user')
        router.push('/user')
      } else {
        //本地存储管理员信息
        localStorage.setItem('path', 'admin')
        router.push('/admin')
      }
    }
    // const res = await createEvent({
    //   eventNumber:'mapgis-hjh-login',
    //   eventType: 'login',
    //   eventLevel: 'info',
    //   eventTime:'string',
    //   eventAddress:'string',
    //   eventCarNumber:'string',
    //   eventDriver:'string',
    //   evnetLngLat:'string',
    // })
    // getEvent()
  }


  //退出登录的方法
  const handleLogout = () => {
    logout()
    username.value = ''
    password.value = ''
    type.value = 'common'

    router.push('/')
  }
  //跳转注册界面的方法
  const handlePush = () => {
    router.push('/register')
  }

  //注册的方法
  const handleRegister = async () => {
    //用户名为空返回提示信息
    if (registerUsername.value === '') {
      ElMessage({
        message: '用户名为空',
        type: 'warning',
        plain: true,
      })
      return
    }
    //密码为空返回提示信息
    if (registerPassword.value === '') {
      ElMessage({
        message: '密码为空',
        type: 'warning',
        plain: true,
      })
      return
    }
    //确认密码为空返回提示信息
    if (registerConfirmPassword.value === '') {
      ElMessage({
        message: '确认密码为空',
        type: 'warning',
        plain: true,
      })
      return
    }
    //密码和确认密码不一致返回提示信息
    if (registerPassword.value !== registerConfirmPassword.value) {
      ElMessage({
        message: '两次输入的密码不一致',
        type: 'error',
        plain: true,
      })
      return
    }
    if (registerPassword.value.length < 6) {
      ElMessage({
        message: '密码长度不能小于6位',
        type: 'warning',
        plain: true,
      })
    }
    //发送注册请求
    const res = await register({
      username: registerUsername.value,
      password: registerPassword.value,
    })
    if (res.code === 200) {
      //注册成功后，跳转到登录页面
      const time = ref(3)
      ElMessage({
        message: `注册成功,${time.value}秒后跳转到登录页面`,
        type: 'success',
        plain: true,
        duration: 3000,
      })
      const timer = setInterval(() => {
        time.value--
        if (time.value < 0) {
          clearInterval(timer)
          router.push('/')
        }
      }, 1000)
    }
  }

  //获取公告的方法
  const getNotice = async () => {
    const res = await getReport()
    console.log(res)
    console.log('获取公告成功')
  }

  //缓冲区的图层
  const layer = new ol.layer.Vector({
    source: new ol.source.Vector({}),
    style: setAreaStyle({ fill: 'rgba(0, 0, 255, 0.8)', stroke: 'blue' }),
    zIndex: 1000,
  })
  //线画笔图层
  const lineLayer = new ol.layer.Vector({
    source: new ol.source.Vector({}),
  })
  //发布公告的方法
  const createReport = () => {
    //清空缓冲区图层
    layer.getSource().clear()
    proxy.$map.removeLayer(layer)
    //清空线画笔图层数据
    lineLayer.getSource().clear()

    let geometry = null
    draw = createDraw({
      type: 'LineString',
      source: lineLayer.getSource(),
    })

    proxy.$map.addInteraction(draw)
    draw.on('drawend', (e) => {
      console.log(e.feature.getGeometry().getCoordinates())
      const lineData = turf.lineString(e.feature.getGeometry().getCoordinates())
      const bufferedLineData = turf.buffer(lineData, 1)
      const line = ToGeoJSON(e.feature)
      // 创建线的缓冲区，第二个参数是缓冲区的半径
      const bufferedLine = turf.buffer(line, 0.3, { units: 'kilometers' })
      const bufferedFeature = JSONToFeature(bufferedLine)

      // 打印结果
      // console.log(layer.getSource().getFeatures()[0].getGeometry())
      console.log(bufferedFeature)
      let service = {
        name: 'guanggu',
        layerId: 0,
      }
      // const geometry = layer.getSource().getFeatures()[0].getGeometry()
      Query.queryByGeom({
        service,
        geometry: bufferedFeature[0].getGeometry(),
        success: (features) => {
          console.log(features)
          //将缓冲区的坐标添加到数据源中
          layer.getSource().addFeatures(features)
          // console.log(layer.getSource())
          features.forEach((feature) => {
            // console.log(feature.values_.values_)
            areaList.value.push({
              name: feature.values_.values_.name,
              // id: feature.values_.values_.ID,
              tel: feature.values_.values_.tel,
            })
          })
          if (areaList.value.length > 0) {
            createNoticeIsShow.value = true //显示发布公告弹窗
          }
          console.log(createNoticeIsShow.value)
        },
      })

      proxy.$map.addLayer(layer)
      proxy.$map.removeInteraction(draw) //画笔移除
      draw = null //画笔置空
    })
    //需要传入title,publisher,content,time(标题，发布人，内容，发布时间)
    // if(type.value === 'traffic'){
    //   const publisher = '交通局'
    // }else if(type.value === 'admin'){
    //   const publisher = '管理员'
    // }
    // createNotice({
    //   title,
    //   publisher,
    //   content,
    //   time,
    // })
  }

  //确认发布按钮的点击事件
  const handleSendNotice = () => {
    if (title.value === '' || textarea.value === '') {
      ElMessage({
        message: '标题或内容不能为空',
        type: 'warning',
        plain: true,
      })
      return
    }
    if (filterTableData.value.length === 0) {
      ElMessage({
        message: '请选择小区',
        type: 'warning',
        plain: true,
      })
      return
    }
    let publisher = ''
    const sendType = localStorage.getItem('type')
    if (sendType === 'traffic') {
      publisher = '交通局'
    } else if (sendType === 'admin') {
      publisher = '管理员'
    }
    createNotice({
      title: title.value,
      content: textarea.value,
      publisher,
      area: filterTableData.value,
      time: new Date().toLocaleString(),
    })
    //发布成功后，清空发布公告的输入框内容
    title.value = ''
    textarea.value = ''
    search.value = ''
    createNoticeIsShow.value = false //隐藏发布公告弹窗

    //清空缓冲区图层
    layer.getSource().clear()
    proxy.$map.removeLayer(layer)
    //清空线画笔图层数据
    lineLayer.getSource().clear()
  }
  const handleCloseNotice = () => {
    //清空缓冲区图层
    layer.getSource().clear()
    proxy.$map.removeLayer(layer)
    //清空线画笔图层数据
    lineLayer.getSource().clear()
    createNoticeIsShow.value = false //隐藏发布公告弹窗
  }

  return {
    type,
    username,
    password,
    registerUsername,
    registerPassword,
    registerConfirmPassword,
    createNoticeIsShow,
    areaList,
    page,
    all,
    title,
    search,
    textarea,
    filterTableData,
    handleLogin,
    handlePush,
    handleRegister,
    getNotice,
    createReport,
    handleLogout,
    handleChange,
    handleSendNotice,
    handleCloseNotice,
  }
})
